const chalk = require('chalk');
const fs = require('fs');
const async = require('async');
const { glob } = require('glob');

/**
 * 字符串是否有数据
 */
const isStringAndHasLength = (val) => {
    if (typeof val === 'string') {
        return val.trim().length > 0;
    }
    return false;
};

/**
 * 文件夹是否存在
 */
const hasFilePromiseHandler = (path) =>
    new Promise((resolve, reject) => {
        fs.access(path, (err) => {
            if (err) {
                resolve(false);
            } else {
                resolve(true);
            }
        });
    });

/**
 * 读取JSON文件
 */
function readJSON(jsonUrl) {
    return new Promise(async (resolve, reject) => {
        try {
            const jsfiles = await glob([jsonUrl]);
            for await (const fileUrl of jsfiles) {
                async.eachSeries(
                    [fileUrl],
                    function (file, callback) {
                        fs.readFile(file, 'utf8', function (err, data) {
                            if (err) {
                                return callback(err);
                            }
                            resolve(JSON.parse(data));
                        });
                    },
                    function (err) {
                        if (err) {
                            console.log('一个错误:', err);
                        }
                    }
                );
            }
        } catch (error) {
            console.log('error- chucuo l', error);
            reject(error);
        }
    });
}

const dealfileObject = {
    type: 'text',
    name: 'dealfile',
    message:
        `请输入要处理的文件夹或者文件, 支持相对/绝对路径(${chalk.red('注意反斜杠陷阱')}) E:\\mine\\niubi.js (` +
        `${chalk.green('使用 & 隔开')}) \n\n` +
        ` 例: ${chalk.magenta('src&src/**/*.{tsx,ts,js,jsx}&public/index.jsx')}\n`,
};

/**
 * 收集中文Promise
 */
const collectInChinese = (fileUrl) =>
    new Promise((resolve, reject) => {
        const arr = [];
        async.eachSeries(
            [fileUrl],
            function (file, callback) {
                fs.readFile(file, 'utf8', function (err, data) {
                    if (err) {
                        reject(err);
                        return callback(err);
                    }
                    // 匹配连续的中文字符
                    const regex = /(?!'\(|"\(|`\()[\u4e00-\u9fa5\，\、\！\，\（\）\：\。]+(?!'\)|"\)|`\))/g;

                    data.replace(/\/\/.*|\/\*[\s\S]*?\*\//g, '').replace(regex, function ($1) {
                        arr.push($1);
                        return $1;
                    });
                    resolve(arr);
                });
            },
            function (err) {
                if (err) {
                    reject(err);
                    console.log('一个错误-23546123:', err);
                } else {
                    reject();
                    console.log(chalk.magenta('文件已处理'));
                }
            }
        );
    });

function formatDate() {
    const now = new Date();
    const year = now.getFullYear();
    const month = (now.getMonth() + 1).toString().padStart(2, '0');
    const day = now.getDate().toString().padStart(2, '0');
    const hours = now.getHours().toString().padStart(2, '0');
    const minutes = now.getMinutes().toString().padStart(2, '0');
    const seconds = now.getSeconds().toString().padStart(2, '0');

    return `${year}${month}${day}_${hours}_${minutes}_${seconds}`;
}

/**
 * 收集11的中文Promise
 */
const collect11InChinese = (fileUrl) =>
    new Promise((resolve, reject) => {
        const arr = [];
        async.eachSeries(
            [fileUrl],
            function (file, callback) {
                fs.readFile(file, 'utf8', function (err, data) {
                    if (err) {
                        reject(err);
                        return callback(err);
                    }
                    // 匹配连续的中文字符
                    const regex = /(?<=\.get\(\'11\'\)\.d\(\')(.*?)(?=\'\))/g;

                    // 匹配即将替换的中文
                    // const regex = /\.get\(\'11\'\)\.d\(\'(.*?)\'\)/g;

                    data.replace(regex, function ($1) {
                        arr.push($1);
                        return $1;
                    });
                    resolve(arr);
                });
            },
            function (err) {
                if (err) {
                    reject(err);
                    console.log('一个错误-23546123:', err);
                } else {
                    reject();
                    console.log(chalk.magenta('文件已处理'));
                }
            }
        );
    });

module.exports = {
    formatDate,
    readJSON,
    dealfileObject,
    collectInChinese,
    collect11InChinese,
    isStringAndHasLength,
    hasFilePromiseHandler,
};
